package com.lenovo.agricultureServer.http;

import java.net.UnknownHostException;

import com.lenovo.agricultureServer.AppConfig;

import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

/**
 * Android components instantiate and control the HTTP server via binding to
 * this service.
 * 
 * @author ccollins
 * 
 */
public class HTTPServerService extends Service {
	private JasonSoapHttpServer jsonHttpd;
	private static final String TAG = "HTTPServerService";
	public static final int DEFAULT_NUM_THREADS = 3; // just used on local LAN
														// and between few
														// devices

	public static final String START_SVC = "lenovoserver.http.StartSVC";
	public static final String STOP_SVC = "lenovoserver.http.StopSVC";

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "HTTPServerService onBind()");
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "onCreate()");
		super.onCreate();
	}

	private static boolean ifrun = false;

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(TAG, "onStart()");
		super.onStart(intent, startId);

		if (!ifrun) {
			try {
				jsonHttpd = new JasonSoapHttpServer(this.getLocalIpAddress(), AppConfig.HTTP_SERVER_PORT, getApplicationContext());
			} catch (UnknownHostException e) {
				System.err.println("New JasonHttpServer instance Exception.\n");
				e.printStackTrace();
			}
			// 启动http服务
			try {
				jsonHttpd.start();
				System.out.println("JasonHttpd Started. ");
			} catch (Exception ioe) {
				System.err.println("Couldn't start JasonHttpd:\n" + ioe);
				ioe.printStackTrace();
				System.exit(-1);
			}
			ifrun = true;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "onStartCommand()");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy()");
		super.onDestroy();
		try {
			// 停止http服务
			jsonHttpd.stop();
			System.out.println("JasonHttpd Stoped.");
			ifrun = false;
			Log.i(TAG, "HTTP SERVER STOPPED");
		} catch (Exception e) {
			Log.e(TAG, "ERROR can't stop JasonHttpd ", e);
		}
	}

	// Get ip address 
	private String getLocalIpAddress() throws UnknownHostException {
		Log.d(TAG, "获取本地IP地址");
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String IP;
		int ipAddress = wifiInfo.getIpAddress();
		IP = intToIp(ipAddress);
		return IP;
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + ((i >> 24) & 0xFF);
	}
}